<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/3/27
 * Time: 8:49
 * Desc: 原料库存管理
 */
namespace app\store\model;
use think\Model;
use think\Db;
use PHPExcel;
use PHPExcel_IOFactory;


class MaterialModel extends Model{
    protected $pk = 'id';
    protected $table = 'ys_material_order';
    protected $field = true;        //自动忽略不存在的字段
//    protected $validate = [
//        ['name', 'require|max:50', '商品名称不能为空|商品名称最多50个字符'],
//        ['subtitle', 'require|max:50', '副标题不能为空|分标题标题最多50个字符'],
//        ['taste', 'require|max:20', '口味不能为空|口味最多20个字符'],
//        ['save_method', 'require|max:20', '保存方法不能为空|保存方法最多20个字符'],
//        ['eat_num', 'require|max:20', '分享人数不能为空|分享人数最多20个字符'],
//        ['good_number', 'require|max:20|unique:goods', '商品货号不能为空|商品货号最多20位|商品货号已被占用，请重新输入'],
//        ['cat_id', 'require', '商品分类不能为空'],
//        ['exp_cat', 'require', '商品扩展分类不能为空'],
//        ['price', 'require|/^([0-9][\d]{0,7})(\.[\d]{1,2})?$/', '商品价格不能为空|商品价格输入错误'],
//        ['is_online', 'require', '请选择是否允许线下销售'],
//        ['status', 'require', '请选择是否上架'],
//        ['description', 'require|max:100', '商品描述不能为空|商品描述最多不能超过100个字符'],
//        ['detail', 'require', '商品详情不能为空']
//    ];
    /**
     * @Author  lingyun
     * @Desc    原料购货订单信息
     * @param $id   原来购货申请订单id
     */
    public function get_order($id){
        return $this->where('id',$id)->find();
    }

    /**
     * @Author  lingyun
     * @Desc    原料购货订单详情
     * @param $id   购货订单id
     * 2018-03-27
     */
    public function order_detail($id){
        $join = [
            ['ys_goods_material b','b.id=a.material_id','LEFT']
        ];
        return db('material_stock_log')->alias('a')->join($join)->where('a.order_id',$id)->field('a.*,b.name,b.unit,b.stock')->select();
    }

    /**
     * @Author  lingyun
     * @Desc    处理原料购货申请订单
     * @Param  $arr  到处理的数据
     * 2018-03-27
     */
    public function deal_order($arr){
        $res = db('material_order')->where('id',$arr['order_id'])->update(['receive_time'=>time(),'status'=>1,'receive_admin'=>session('user.id'),'is_duizhang'=>$arr['is_duizhang']]);
        $data = $this->create_deal_order_arr($arr);     //获取入库的处理数据
        if($data['code'] == 0){         //错误
            return ['code'=>0,'msg'=>$data['msg'],'receive_price'=>$data['receive_price']];
        }
        return ['code'=>1,'msg'=>$data['msg'],'receive_price'=>$data['receive_price']];
    }

    /**
     * @Author  lingyun
     * @Desc    创建处理原料订单入库数据
     * @param $arr  待处理的数据
     * 2018-03-27
     */
    private function create_deal_order_arr($arr){
        $stock = $arr['stock'];             //原料原始库存
        $del_num = $arr['del_num'];         //购货数量
        $res_num = $arr['res_num'];         //实际变更数量
        $dif_num = $arr['dif_num'];         //差异数 -- 允许负值
        $price = $arr['price'];             //原料单价
        $id = $arr['id'];                   //material_stock_log
        $material_id = $arr['material_id']; //原料主键id
        $data1 = [];                   //原料库存记录入库数据
        $data2 = [];                   //原料信息入库数据
        $receive_price = 0;
        foreach($id as $k=>$v){
            if($res_num[$k] === ''){
                return ['code'=>0,'msg'=>'请输入实际变更数量'];
            }
            $data1[$k]['id'] = $v;
            $data1[$k]['res_num'] = $res_num[$k];
            $data1[$k]['dif_num'] = $dif_num[$k];
            $data1[$k]['receive_time'] = time();
            if($arr['is_duizhang'] == 1){           //暂未对账
//                $data1[$k]['receive_prcie'] = $price[$k]*$res_num[$k];
//                $data1[$k]['receive_signal_price'] = $price[$k];
                $receive_price += $price[$k];
            }else{              //确认对账
                $data1[$k]['receive_price'] = $arr['r_price'][$k];
                $data1[$k]['receive_signal_price'] = $arr['r_s_price'][$k];
                $receive_price += $arr['r_price'][$k];
            }

            if($arr['order_type'] == 1){        //购货
                $data1[$k]['cur_num'] = $stock[$k]+$res_num[$k];
                $data1[$k]['remark'] = '购货'.$del_num[$k].'，实收'.$res_num[$k]."，差异数".$dif_num[$k];
            }else{
                $data1[$k]['cur_num'] = $stock[$k]-$res_num[$k];
                $data1[$k]['remark'] = '生产使用'.$del_num[$k].'，实际使用'.$res_num[$k]."，差异数".$dif_num[$k];
            }

            $data2[$k]['id'] = $material_id[$k];
            $data2[$k]['stock'] = $data1[$k]['cur_num'];
        }
        $msg = [
            'data1'=>$data1,
            'data2'=>$data2
        ];
//        halt($receive_price);
        return ['code'=>1,'msg'=>$msg,'receive_price'=>$receive_price];
    }

    /**
     * @Author  lingyun
     * @Desc    导出订单详情
     * @param $id      导出的订单id
     * 2018-03-27
     */
    public function export_detail($id){
        $order = db('material_order')->where('id',$id)->find();      //订单信息
        $data = db('material_stock_log')->alias('a')->join('ys_goods_material b','a.material_id=b.id','LEFT')->where('order_id',$id)->field('a.*,b.name,b.unit')->select();   //订单详情

        $filename = '原料订单详情'.date('YmdHis').'.xls';

        $objPHPExcel = new PHPExcel();//新建一个表
        $objSheet = $objPHPExcel->getActiveSheet();//获得当前活动Sheet
        $objSheet->setTitle("原料订单详情");


        $title = $order['order_sn'];
        if($order['type'] == 1){
            $title .= " - 购货";
        }else{
            $title .= " - 生产";
        }
        $title .= " - ".$order['price'];
        if($order['receive_time'] == ''){
            $title .= " - 未处理";
        }else{
            $title .= " - 已处理";
        }

        $objSheet->setCellValue('A1', $title);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:G1');      //合并
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(     //加粗和居中
            array(
                'font' => array (
                    'bold' => true
                ),
//                'alignment' => array(
//                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER
//                )
            )
        );


        $objSheet
            ->setCellValue('A2', '原料')
            ->setCellValue('B2', '单位')
            ->setCellValue('C2', '申请数量')
            ->setCellValue('D2', '实际数量')
            ->setCellValue('E2', '差异数')
            ->setCellValue('F2', '原料单价')
            ->setCellValue('G2', '原料总价');


        $j = 3;     //从第三行开始

        foreach ($data as $key => $value) {
            if(empty($value['res_num'])){
                $value['res_num'] = '未处理';
            }
            if(empty($value['dif_num'])){
                $value['dif_num'] = '未处理';
            }
            $objSheet
                ->setCellValue('A' . $j, $value['name'])
                ->setCellValue('B' . $j, $value['unit'])
                ->setCellValue('C' . $j, $value['del_num'])
                ->setCellValue('D' . $j, $value['res_num'])
                ->setCellValue('E' . $j, $value['dif_num'])
                ->setCellValue('F' . $j, $value['signal_price'])
                ->setCellValue('G' . $j, $value['price']);

            $j ++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $objWriter->save("php://output");
    }


}